package com.xinggq.user.service.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinggq.common.CommonResult;
import com.xinggq.common.page.PageCondition;
import com.xinggq.common.utils.Validate;
import com.xinggq.user.service.dto.tenant.TenantCreateRequest;
import com.xinggq.user.service.dto.tenant.TenantQueryRequest;
import com.xinggq.user.service.dto.tenant.TenantUpdateRequest;
import com.xinggq.user.service.entity.SysTenantEntity;
import com.xinggq.user.service.service.TenantService;
import com.xinggq.user.service.dto.tenant.TenantVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


/**
 * 租户管理控制器
 *
 * @author xinggq
 * @since 2025-01-01
 */
@Slf4j
@RestController
@RequestMapping("/api/tenant")
@RequiredArgsConstructor
@Tag(name = "租户管理API", description = "提供租户增删改查等管理功能")
public class TenantController {

  private final TenantService tenantService;

  /**
   * 创建租户
   */
  @PostMapping("/create")
  @Operation(summary = "创建租户", description = "创建新的租户")
  public CommonResult<TenantVO> createTenant(@Valid @RequestBody TenantCreateRequest request) {
    log.info("接收到创建租户请求: {}", request);
    SysTenantEntity sysTenantEntity = SysTenantEntity.fromTenantVO(request);
    SysTenantEntity createdTenant = tenantService.create(sysTenantEntity);
    log.info("租户创建成功，ID: {}", createdTenant.getId());
    return CommonResult.ok(createdTenant.toTenantVO());
  }

  /**
   * 更新租户
   */
  @PostMapping("/update")
  @Operation(summary = "更新租户", description = "更新指定租户信息")
  public CommonResult<TenantVO> updateTenant(@Valid @RequestBody TenantUpdateRequest request) {

    // 转换为实体对象
    SysTenantEntity tenant = new SysTenantEntity();
    tenant.setId(request.id());
    if (StringUtils.hasText(request.tenantName())) {
      tenant.setTenantName(request.tenantName());
    }
    if (StringUtils.hasText(request.domain())) {
      tenant.setDomain(request.domain());
    }
    if (StringUtils.hasText(request.contactPerson())) {
      tenant.setContactPerson(request.contactPerson());
    }
    if (StringUtils.hasText(request.contactPhone())) {
      tenant.setContactPhone(request.contactPhone());
    }
    if (StringUtils.hasText(request.contactEmail())) {
      tenant.setContactEmail(request.contactEmail());
    }
    if (request.expireTime() != null) {
      tenant.setExpireTime(request.expireTime());
    }
    if (request.maxUsers() != null) {
      tenant.setMaxUsers(request.maxUsers());
    }
    if (StringUtils.hasText(request.description())) {
      tenant.setDescription(request.description());
    }
    // 更新租户
    SysTenantEntity updatedTenant = tenantService.update(tenant);

    log.info("租户更新成功，ID: {}", updatedTenant.getId());
    return CommonResult.ok(updatedTenant.toTenantVO());
  }

  /**
   * 根据ID获取租户
   */
  @GetMapping("/get/{id}")
  @Operation(summary = "获取租户详情", description = "根据ID获取租户详细信息")
  public CommonResult<TenantVO> getTenantById(
      @NotNull(message = "租户ID不能为空")
      @Parameter(description = "租户ID")
      @PathVariable("id") Long id)
  {
    log.info("接收到获取租户详情请求，ID: {}", id);

    SysTenantEntity tenant = tenantService.getById(id);
    Validate.objectNotNull(tenant, "租户不存在");

    return CommonResult.ok(tenant.toTenantVO());
  }

  /**
   * 分页查询租户
   */
  @PostMapping("/page")
  @Operation(summary = "分页查询租户", description = "根据条件分页查询租户列表")
  public CommonResult<IPage<TenantVO>> getTenantPage(@Valid @RequestBody PageCondition<TenantQueryRequest> request) {
    return CommonResult.ok(tenantService.page(request));
  }

  /**
   * 启用租户
   */
  @GetMapping("/enable")
  @Operation(summary = "启用租户", description = "启用指定租户")
  public CommonResult<Void> enableTenant(
      @NotNull(message = "租户ID不能为空")
      @RequestParam("id") String id) {
    log.info("接收到启用租户请求，ID: {}", id);

    tenantService.enable(Long.valueOf(id));

    log.info("租户启用成功，ID: {}", id);
    return CommonResult.ok();
  }

  /**
   * 禁用租户
   */
  @GetMapping("/disable")
  @Operation(summary = "禁用租户", description = "禁用指定租户")
  public CommonResult<Void> disableTenant(
      @NotNull(message = "租户ID不能为空")
      @RequestParam("id") String id) {
    log.info("接收到禁用租户请求，ID: {}", id);

    tenantService.disable(Long.valueOf(id));

    log.info("租户禁用成功，ID: {}", id);
    return CommonResult.ok();
  }

  /**
   * 检查租户编码是否存在
   */
  @GetMapping("/check-code")
  @Operation(summary = "检查租户编码", description = "检查租户编码是否已存在")
  public CommonResult<Boolean> checkTenantCode(
      @Size(max = 50, message = "租户编码长度不能超过50个字符")
      @Pattern(regexp = "^[A-Z0-9_]+$", message = "租户编码只能包含大写字母、数字和下划线")
      @NotBlank(message = "租户编码不能为空")
      @RequestParam("tenantCode") String tenantCode,
      @RequestParam(value = "excludeId", required = false) Long excludeId) {
    log.info("接收到检查租户编码请求，编码: {}, 排除ID: {}", tenantCode, excludeId);

    boolean exists = tenantService.existsByTenantCode(tenantCode, excludeId);

    return CommonResult.ok(exists);
  }
}